package parser;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class TrecEvalParser {
	
	public static Map<String, Map<String,Double>> parseQueryMeasure(String line)
	{
		String[] tokens = line.split("\\s+" );
		
		Map<String,Double> measureMap = new HashMap<String,Double>();
		measureMap.put(tokens[0], Double.parseDouble(tokens[2]));
		
		Map<String, Map<String,Double>> queryMeasureMap = new HashMap<String, Map<String,Double>>();
		queryMeasureMap.put(tokens[1], measureMap);
		return queryMeasureMap;
	}
	
	public static Map<String, Map<String,Double>> parseMethodEval(File trecEvalFile) throws FileNotFoundException
	{
		Scanner scanner = new Scanner(trecEvalFile);
		
		Map<String, Map<String,Double>> methodTrecEval = new HashMap<String, Map<String,Double>>();
		
		while(scanner.hasNext())
		{
			Map<String, Map<String,Double>> queryMeasureMap = parseQueryMeasure(scanner.nextLine());
			String qno = queryMeasureMap.keySet().toArray(new String[1])[0];
			
			if (methodTrecEval.containsKey(qno))
			{
				methodTrecEval.get(qno).putAll(queryMeasureMap.get(qno));
				methodTrecEval.put(qno, methodTrecEval.get(qno));
				
				
			} else {
				methodTrecEval.put(qno, queryMeasureMap.get(qno));
			}
		}
		
		scanner.close();
		return methodTrecEval;
		
	}
	
	public static Map<String,Map<String, Map<String,Double>>> parseEvaluation(File[] methodsTrecEvals) throws FileNotFoundException
	{
		Map<String,Map<String, Map<String,Double>>> methodsEvals = new HashMap<>();
		
		for (File file : methodsTrecEvals)
		{
			methodsEvals.put(file.getName(), parseMethodEval(file));
		}
		
		return methodsEvals;
	}

}
